var http = require('http');
var util = require('util');
var url = require('url');
var fs = require('fs');
var port = 80;
var ip = '127.0.0.1';
http.createServer(function (request, response) {
	response.statusCode = 200;
	response.statusMessage = "It's not find";
	response.setHeader('Server','private server')
	response.setHeader('Content-Type', 'text/html');
	var ext = request.url.substr(request.url.lastIndexOf(".")+1);
	var exts = {
		html:'text/html',
		js:'application/x-javascript',
		jpg:'image/jpeg',
		css:'text/css'
	}
	if (exts[ext]==null) {
		exts[ext]="text/plain"
	}
	var data ="404 网页错误"
	var setname = "帅气的留言板"
	var p = url.parse(request.url,true)
	response.setHeader('Content-Type', exts[ext]);
	if (p. pathname == "/index.html") {
		try{
			data = fs.readFileSync('html'+request.url,'utf8');
			data = data.replace(/%title/g,setname)
			item = fs.readFileSync('data.json','utf8');
			item = JSON.parse(item);
			var s="";
			for (var i = 0; i <item.length; i++) {
				s+= '<div class="container">';
				s+=	'<h6>'+item[i].name+'<span>'+item[i].time+'</span></h6>';
				s+=	'<p>'+item[i].text+'</p>';
				s+=	'</div>';
			}
			data = data.replace(/%main/g,s)
		}catch(e){
		}
	}else if (p. pathname == "/form.html") {
		data = fs.readFileSync('.'+request.url,'utf8');
	}else if (p.pathname =="/addmessage") {
		text = p.query.text;
		name = p.query.name;
		item = JSON.parse(fs.readFileSync('data.json','utf8'));
		var date =	new Date;
		date = JSON.stringify(date);
		date = date.substr(1,10)
		item.push({
			text:text,
			name:name,
			time:date
		})
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		response.writeHead(302,{
			'location':'/index.html'
		});
	}else if (p.pathname =="/delmessage") {
		data = p.query.id;
	}
	response.end(data);
}).listen(port);

// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,port);

























// if (ext=='css') {
	// 	response.setHeader('Content-Type', 'text/css');
	// }else if (ext=='.js') {
	// 	response.setHeader('Content-Type', 'application/x-javascript');
	// }else if (ext=='jpg') {
	// 	response.setHeader('Content-Type', 'image/jpeg');
	// }else if (ext=='nts') {
	// 	response.setHeader('Content-Type', 'application/vnd.ms-fontobject');
	// }